﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>加载基础地图数据（ArcGISOnline的矢量、瓦片）</title>
    <link href="../../libs/ol/ol.css" rel="stylesheet" type="text/css" />
    <script src="../../libs/ol/ol.js" type="text/javascript"></script>
<!--  <script src="../../libs/ol/ol-debug.js" type="text/javascript"></script>-->
    <!--  引入第三方插件库 -->
    <script src="../../libs/jquery-1.11.2.min.js" type="text/javascript"></script>
    <style type="text/css">
        body,html,div,ul,li,iframe,p,img{
            border:none;padding:0;margin:0;
        }
        #map{
            width:100%;
            height:550px;
        }
        #menu{
            width:100%;
            height:20px;         
            padding:5px 0px;
            font-size:14px;
            font-family:"微软雅黑";
            left:10px;    
        }
        #menu ul{
            float:left;
        }
        #menu ul li{
            float:left;
            list-style:none;
            margin:0px 15px; 
        }
        #mouse-position{
            float:right;
            margin: 0px 15px; 
        }
    </style>
</head>
<body>
    <div id="menu">
        <ul>
            <li>
                <label class="checkbox" ><input type="radio" name="maps" value="arcgis"/>ArcGIS地图</label>
                <select id="arcgisType">
                    <option value="MapServer" selected="selected">MapServer在线瓦片数据</option>                 
                    <option value="arcgisOnline">arcgisOnline在线瓦片数据</option>
                    <option value="RestFeatureService">ArcGIS REST Feature Service</option>
                </select>
            </li>
        </ul>
        <div id="mouse-position" class="custom-mouse-position" ></div>
    </div>  
    <div id="map">
    </div>
    <script type="text/javascript">
        var arcGISLayers; //arcGIS图层
        var arcGISSource; //arcGIS数据源

        var view = new ol.View({
            //projection: ol.proj.get('EPSG:4326'),
            center: [0, 0], //地图初始中心点
            zoom: 4 //地图初始显示级别
        });
        //实例化Map对象加载地图
        var map = new ol.Map({
            target: 'map', //地图容器div的ID
            //地图容器中加载的图层
            layers: arcGISLayers,
            //地图视图设置
            view: view
        });
        //添加坐标
        var mousePositionControl = new ol.control.MousePosition({
            coordinateFormat: ol.coordinate.createStringXY(2),
            className: 'custom-mouse-position',
            target: document.getElementById('mouse-position'),
            undefinedHTML: '&nbsp;'
        });
        map.addControl(mousePositionControl);

        $("input[type='radio'][name='maps']").get(0).checked = true; //默认选中
        var select = document.getElementById('arcgisType');
        select.addEventListener('change', onChange); //添加地图类型选项的事件监听
        loadArcGISMap(select.value); //默认加载选中类型的地图

        //数据类型切换处理函数
        function onChange() {
            map.removeLayer(arcGISLayers); //移除图层
            loadArcGISMap(select.value); //加载当前类型的地图数据
        }

        function loadArcGISMap(type) { 
            //移除当前已有图层
            var cLayers = map.getLayers();
            if (cLayers != null) { 
                for (var i = 0; i < cLayers.length; i++) {
                    map.removeLayer(cLayers[i]);
                }
            }
            //加载ArcGIS MapServer地图
            if (type == "MapServer") {
                arcGISSource = new ol.source.TileArcGISRest({
                    url: 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + 'Specialty/ESRI_StateCityHighway_USA/MapServer'
                });
                arcGISLayers = new ol.layer.Tile({
                    source: arcGISSource,
                    extent: [-13884991, 2870341, -7455066, 6338219]
                });
                map.addLayer(arcGISLayers); //添加瓦片地图图层   
                setMapView([-10997148, 4569099], 5);
            }
            //加载arcgisOnline地图
            else if (type == "arcgisOnline") {
                var attribution = new ol.Attribution({
                    html: 'Tiles &copy; <a href="http://services.arcgisonline.com/ArcGIS/' + 'rest/services/World_Topo_Map/MapServer">ArcGIS</a>'
                });
                arcGISLayers = new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        attributions: [attribution],
                        url: 'http://server.arcgisonline.com/ArcGIS/rest/services/' + 'World_Topo_Map/MapServer/tile/{z}/{y}/{x}'
                    })
                })
                map.addLayer(arcGISLayers); //添加地图图层   
                setMapView(ol.proj.fromLonLat([-121.1, 47.5]), 7);
            }
            //加载ArcGIS REST矢量要素服务地图
            else if (type == "RestFeatureService") {
                var serviceUrl = 'http://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/' + 'services/PDX_Pedestrian_Districts/FeatureServer/';
                var layer = '0';
                var esrijsonFormat = new ol.format.EsriJSON();//ESRI的JSON数据格式解析类
                //实例化矢量数据源对象（AJAX请求REST服务）
                var arcGISSource = new ol.source.Vector({
                    loader: function (extent, resolution, projection) {
                        var url = serviceUrl + layer + '/query/?f=json&' +
                            'returnGeometry=true&spatialRel=esriSpatialRelIntersects&geometry=' +
                            encodeURIComponent('{"xmin":' + extent[0] + ',"ymin":' +
                                extent[1] + ',"xmax":' + extent[2] + ',"ymax":' + extent[3] +
                                ',"spatialReference":{"wkid":102100}}') +
                            '&geometryType=esriGeometryEnvelope&inSR=102100&outFields=*' +
                            '&outSR=102100';
                        $.ajax({ url: url, dataType: 'jsonp', success: function (response) {
                            if (response.error) {
                                alert(response.error.message + '\n' + response.error.details.join('\n'));
                            } else {
                                // 从请求结果中读取要素
                                var features = esrijsonFormat.readFeatures(response, {
                                    featureProjection: projection
                                });
                                if (features.length > 0) {
                                    arcGISSource.addFeatures(features);//将要素设置到数据源中
                                }
                            }
                        } 
                        });
                    },
                    strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({
                        tileSize: 512
                    }))
                });
                arcGISLayers = new ol.layer.Vector({
                    source: arcGISSource
                });
                map.addLayer(arcGISLayers); //添加地图图层   
                setMapView(ol.proj.fromLonLat([-121.1, 47.5]), 5);
            }     
        }
        /**
        * 重新设置地图视图
        * @param {ol.Coordinate} center 中心点
        * @param {number} zoom 缩放级数
        */
        function setMapView(center, zoom) {
            var view = map.getView(); //获取地图视图
            view.setCenter(center); //平移地图
            view.setZoom(zoom); //地图缩放
        }     
    </script>
</body>
</html>
